package com.thuanpq.SQLite_Demo;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SQLite_Demo extends ListActivity {
	DBAdapter mDBHelper;
	Cursor mCursor;
	ArrayAdapter<String> array;
	ArrayAdapter<String> arraylist;
	Button btnReload;
	Button btnInsert;
	Button btnTest;
	EditText txtName;
	EditText txtType;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btnReload = (Button) findViewById(R.id.btnReload);
		btnInsert = (Button) findViewById(R.id.btnInsert);
		btnTest = (Button) findViewById(R.id.btnTest);
		txtName = (EditText) findViewById(R.id.txtName);
		txtType = (EditText) findViewById(R.id.txtType);
		mDBHelper = new DBAdapter(this);
		mDBHelper.open();
		loadData();

		btnInsert.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(
						getApplication(),
						"Insert: " + txtName.getText().toString() + "-"
								+ txtType.getText().toString(),
						Toast.LENGTH_SHORT).show();
				mDBHelper.createField(txtName.getText().toString(), txtType
						.getText().toString());
				loadData();
			}
		});

		btnReload.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				loadData();
			}
		});
	}

	public void loadData() {
		try {
			Log.e("sqlite", "1");
			Cursor c = mDBHelper.getAllField();
			Log.e("sqlite", "4");
			if (c.getCount() > 0) {
				Log.e("sqlite", "5");
				c.moveToFirst();
			}
			array = new ArrayAdapter<String>(getApplication(),
					android.R.layout.simple_list_item_1);
			do {
				String name = c.getString(c.getColumnIndex("account_name"));
				String type = c.getString(c.getColumnIndex("account_type"));
				array.add(name + " \n " + type);
			} while (c.moveToNext());
			setListAdapter(array);
		} catch (Exception e) {
			Toast.makeText(getApplication(), "Not found database",
					Toast.LENGTH_LONG).show();
		}
	}
}